{% extends "base.html" %}

{% block title %}公共方法管理{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/codemirror.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/theme/monokai.min.css">
<style>

    
    .method-name {
        font-weight: 600;
        color: #495057;
    }
    
    .method-description {
        color: #6c757d;
        font-size: 0.9em;
        max-width: 300px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    
    .method-tags {
        display: flex;
        flex-wrap: wrap;
        gap: 5px;
        margin-top: 10px;
    }
    
    .method-tag {
        background: #f8f9fa;
        border: 1px solid #dee2e6;
        border-radius: 12px;
        padding: 2px 8px;
        font-size: 12px;
        color: #6c757d;
    }
    
    .status-badge {
        padding: 4px 8px;
        border-radius: 12px;
        font-size: 12px;
        font-weight: 500;
    }
    
    .status-active {
        background: #d4edda;
        color: #155724;
    }
    
    .status-inactive {
        background: #f8d7da;
        color: #721c24;
    }
    
    .public-badge {
        background: #d1ecf1;
        color: #0c5460;
    }
    
    .private-badge {
        background: #fff3cd;
        color: #856404;
    }
    
    .CodeMirror {
        border: 1px solid #ddd;
        border-radius: 4px;
        min-height: 300px;
        max-height: 500px;
        height: auto;
    }
    
    .CodeMirror-scroll {
        min-height: 300px;
        max-height: 500px;
    }
    
    /* 确保模态框中的编辑器正确显示 */
    .modal-xl .CodeMirror {
        width: 100%;
    }
    

    
    .search-filters {
        background: #f8f9fa;
        padding: 20px;
        border-radius: 8px;
        margin-bottom: 20px;
    }
    
    .method-actions {
        display: flex;
        gap: 5px;
        justify-content: flex-start;
    }
    
    .method-actions .btn {
        padding: 4px 8px;
        font-size: 12px;
    }
    
    .import-code {
        background: #f8f9fa;
        border: 1px solid #dee2e6;
        border-radius: 4px;
        padding: 4px 8px;
        font-family: 'Courier New', monospace;
        font-size: 11px;
        color: #495057;
        display: inline-block;
        max-width: 250px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
    }
    
    .method-badges {
        display: flex;
        gap: 5px;
        flex-wrap: wrap;
    }
    
    .method-info {
        display: flex;
        flex-direction: column;
        gap: 2px;
    }
    
    .method-usage {
        color: #6c757d;
        font-size: 0.8em;
    }
</style>
{% endblock %}

{% block content %}
<!-- 设置全局变量 -->
<script>
// 设置当前用户信息为全局变量
window.currentUser = {
    isAuthenticated: {{ 'true' if current_user.is_authenticated else 'false' }},
    id: {{ current_user.id if current_user.is_authenticated else 'null' }},
    username: '{{ current_user.username if current_user.is_authenticated else "" }}'
};
console.log('当前用户信息:', window.currentUser);
</script>
<div class="container-fluid" data-current-user-id="{{ current_user.id if current_user.is_authenticated else '' }}">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="fas fa-code"></i> 公共方法管理</h2>
                <div>
                    <button class="btn btn-success" data-bs-toggle="modal" data-bs-target="#createMethodModal">
                        <i class="fas fa-plus"></i> 新建方法
                    </button>
                </div>
            </div>
            
            <!-- 搜索和过滤 -->
            <div class="search-filters">
                <div class="row">
                    <div class="col-md-4">
                        <div class="form-group">
                            <label for="searchInput">搜索方法</label>
                            <input type="text" class="form-control" id="searchInput" placeholder="搜索名称或描述...">
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="viewMode">查看模式</label>
                            <select class="form-control" id="viewMode">
                                <option value="my">我的方法</option>
                                <option value="public">公开方法</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <label for="sortBy">排序方式</label>
                            <select class="form-control" id="sortBy">
                                <option value="updated_at">最近更新</option>
                                <option value="created_at">创建时间</option>
                                <option value="name">名称</option>
                            </select>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            <label>&nbsp;</label>
                            <button class="btn btn-outline-primary form-control" onclick="loadMethods()">
                                <i class="fas fa-search"></i> 搜索
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 方法列表 -->
            <div class="card">
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-striped" id="methodsTable">
                            <thead>
                                <tr>
                                    <th>方法名</th>
                                    <th>用户名</th>
                                    <th>描述</th>
                                    <th>状态</th>
                                    <th>可见度</th>
                                    <th>创建时间</th>
                                    <th>更新时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="methodsList">
                                <tr>
                                    <td colspan="8" class="text-center py-5">
                                        <div class="spinner-border text-primary" role="status">
                                            <span class="visually-hidden">加载中...</span>
                                        </div>
                                        <p class="mt-2 text-muted">正在加载公共方法...</p>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    
                    <!-- 分页 -->
                    <nav aria-label="方法分页" id="paginationNav" style="display: none;">
                        <ul class="pagination justify-content-center" id="pagination">
                        </ul>
                    </nav>
                </div>
            </div>
            
            <!-- 分页 -->
            <nav aria-label="方法分页" id="paginationNav" style="display: none;">
                <ul class="pagination justify-content-center" id="pagination">
                </ul>
            </nav>
        </div>
    </div>
</div>

<!-- 创建/编辑方法模态框 -->
<div class="modal fade" id="createMethodModal" tabindex="-1" aria-labelledby="createMethodModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createMethodModalLabel">新建公共方法</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="methodForm">
                    <input type="hidden" id="methodId">
                    <div class="form-group mb-3">
                        <label for="methodName" class="form-label">方法名称 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="methodName" required>
                    </div>
                    
                    <div class="form-group mb-3">
                        <label for="methodDescription" class="form-label">描述</label>
                        <textarea class="form-control" id="methodDescription" rows="3" 
                                  placeholder="描述这个公共方法的功能和用途..."></textarea>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <div class="form-check mb-3">
                                <input class="form-check-input" type="checkbox" id="isPublic">
                                <label class="form-check-label" for="isPublic">
                                    公开方法（其他用户可见）
                                </label>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-check mb-3">
                                <input class="form-check-input" type="checkbox" id="isActive" checked>
                                <label class="form-check-label" for="isActive">
                                    激活状态
                                </label>
                            </div>
                        </div>
                    </div>
                    
                    <div class="form-group mb-3">
                        <label for="methodTags" class="form-label">标签</label>
                        <input type="text" class="form-control" id="methodTags" 
                               placeholder="用逗号分隔的标签，如：工具,数据处理,算法">
                    </div>
                    
                    <div class="form-group mb-3">
                        <label for="methodContent" class="form-label">Python代码 <span class="text-danger">*</span></label>
                        <textarea id="methodContent" required></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="saveMethod()">保存</button>
            </div>
        </div>
    </div>
</div>



<!-- 查看方法详情模态框 -->
<div class="modal fade" id="viewMethodModal" tabindex="-1" aria-labelledby="viewMethodModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="viewMethodModalLabel">查看公共方法</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div id="viewMethodContent">
                    <!-- 方法详情内容 -->
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" id="editMethodBtn" onclick="editMethod()">编辑</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.2/mode/python/python.min.js"></script>

<script>
let codeEditor;
let currentPage = 1;
let currentMethodId = null;

$(document).ready(function() {
    // 初始化代码编辑器
    initCodeEditor();
    
    // 加载方法列表
    loadMethods();
    
    // 绑定事件
    bindEvents();
});

function initCodeEditor() {
    codeEditor = CodeMirror.fromTextArea(document.getElementById('methodContent'), {
        mode: 'python',
        theme: 'monokai',
        lineNumbers: true,
        indentUnit: 4,
        lineWrapping: true,
        autoCloseBrackets: true,
        matchBrackets: true,
        viewportMargin: Infinity, // 确保所有内容都能正确渲染
        extraKeys: {
            "Ctrl-Space": "autocomplete",
            "Tab": function(cm) {
                if (cm.somethingSelected()) {
                    cm.indentSelection("add");
                } else {
                    cm.replaceSelection("    ", "end");
                }
            }
        }
    });
}

function bindEvents() {
    // 搜索输入框回车事件
    $('#searchInput').on('keypress', function(e) {
        if (e.which === 13) {
            loadMethods();
        }
    });
    
    // 查看模式切换
    $('#viewMode').on('change', function() {
        loadMethods();
    });
    
    // 模态框显示时刷新编辑器
    $('#createMethodModal').on('shown.bs.modal', function() {
        if (codeEditor) {
            // 延迟刷新，确保模态框完全显示
            setTimeout(function() {
                codeEditor.refresh();
                codeEditor.focus();
            }, 100);
        }
    });
    
    // 模态框关闭时重置表单
    $('#createMethodModal').on('hidden.bs.modal', function() {
        resetMethodForm();
        // 确保移除任何残留的遮罩
        $('.modal-backdrop').remove();
        $('body').removeClass('modal-open');
        $('body').css('padding-right', '');
    });
    
    // 查看模态框关闭时清理遮罩
    $('#viewMethodModal').on('hidden.bs.modal', function() {
        // 确保移除任何残留的遮罩
        $('.modal-backdrop').remove();
        $('body').removeClass('modal-open');
        $('body').css('padding-right', '');
    });
}

function loadMethods(page = 1) {
    currentPage = page;
    const search = $('#searchInput').val();
    const showPublic = $('#viewMode').val() === 'public';
    
    $.ajax({
        url: '/dashboard/api/common-methods',
        method: 'GET',
        data: {
            page: page,
            per_page: 12,
            search: search,
            show_public: showPublic
        },
        success: function(response) {
            if (response.success) {
                renderMethods(response.data.methods);
                renderPagination(response.data.pagination);
            } else {
                showToast('加载失败: ' + response.message, 'error');
            }
        },
        error: function() {
            showToast('加载失败: 网络错误，请稍后重试', 'error');
        }
    });
}

function renderMethods(methods) {
    const container = $('#methodsList');
    const viewMode = $('#viewMode').val();
    
    if (methods.length === 0) {
        const emptyMessage = viewMode === 'public' ? 
            '<p class="text-muted">暂无公开的公共方法</p>' : 
            '<p class="text-muted">点击"新建方法"开始创建您的第一个公共方法</p>';
        
        container.html(`
            <tr>
                <td colspan="8" class="text-center py-5">
                    <i class="fas fa-code fa-3x text-muted mb-3"></i>
                    <h5 class="text-muted">暂无公共方法</h5>
                    ${emptyMessage}
                </td>
            </tr>
        `);
        return;
    }
    
    // 使用全局变量获取当前用户ID
    const currentUserId = window.currentUser ? window.currentUser.id : null;
    console.log('当前用户ID:', currentUserId, '查看模式:', viewMode);
    
    let html = '';
    
    methods.forEach(method => {
        console.log('方法:', method.name, '用户ID:', method.user_id, '当前用户ID:', currentUserId, '匹配:', method.user_id == currentUserId);
        const tags = method.tags ? JSON.parse(method.tags) : [];
        const statusClass = method.is_active ? 'status-active' : 'status-inactive';
        const statusText = method.is_active ? '激活' : '未激活';
        const visibilityClass = method.is_public ? 'public-badge' : 'private-badge';
        const visibilityText = method.is_public ? '公开' : '私有';
        
        html += `
            <tr>
                <td>
                    <div class="method-info">
                        <div class="method-name">${escapeHtml(method.name)}</div>
                        ${tags.length > 0 ? `
                            <div class="method-tags mt-1">
                                ${tags.map(tag => `<span class="method-tag">${escapeHtml(tag)}</span>`).join('')}
                            </div>
                        ` : ''}
                    </div>
                </td>
                <td>
                    <div class="method-user">
                        <i class="fas fa-user"></i> ${escapeHtml(method.user_name)}
                    </div>
                </td>
                <td>
                    <div class="method-description" title="${method.description ? escapeHtml(method.description) : '暂无描述'}">
                        ${method.description ? escapeHtml(method.description.substring(0, 60)) + (method.description.length > 60 ? '...' : '') : '暂无描述'}
                    </div>
                </td>
                <td>
                    <span class="status-badge ${statusClass}">${statusText}</span>
                </td>
                <td>
                    <span class="status-badge ${visibilityClass}">${visibilityText}</span>
                </td>
                <td>
                    <small class="text-muted">
                        ${formatDateTime(method.created_at)}
                    </small>
                </td>
                <td>
                    <small class="text-muted">
                        ${formatDateTime(method.updated_at)}
                    </small>
                </td>
                <td>
                    <div class="method-actions">
                        <button class="btn btn-sm btn-outline-primary" onclick="viewMethod(${method.id})" title="查看">
                            <i class="fas fa-eye"></i>
                        </button>
                        ${(viewMode === 'my' && method.user_id == currentUserId) ? `
                            <button class="btn btn-sm btn-outline-success" onclick="editMethod(${method.id})" title="编辑">
                                <i class="fas fa-edit"></i>
                            </button>
                        ` : ''}
                        <button class="btn btn-sm btn-outline-info" onclick="copyImportStatement('${escapeHtml(method.import_statement)}')" title="复制引用语句">
                            <i class="fas fa-copy"></i>
                        </button>
                        ${(viewMode === 'my' && method.user_id == currentUserId) ? `
                            <button class="btn btn-sm btn-outline-danger" onclick="deleteMethod(${method.id}, '${escapeHtml(method.name)}')" title="删除">
                                <i class="fas fa-trash"></i>
                            </button>
                        ` : ''}
                    </div>
                </td>
            </tr>
        `;
    });
    
    container.html(html);
}

function renderPagination(pagination) {
    const nav = $('#paginationNav');
    const container = $('#pagination');
    
    if (pagination.pages <= 1) {
        nav.hide();
        return;
    }
    
    nav.show();
    let html = '';
    
    // 上一页
    if (pagination.has_prev) {
        html += `<li class="page-item"><a class="page-link" href="#" onclick="loadMethods(${pagination.page - 1})">上一页</a></li>`;
    }
    
    // 页码
    const startPage = Math.max(1, pagination.page - 2);
    const endPage = Math.min(pagination.pages, pagination.page + 2);
    
    for (let i = startPage; i <= endPage; i++) {
        const activeClass = i === pagination.page ? 'active' : '';
        html += `<li class="page-item ${activeClass}"><a class="page-link" href="#" onclick="loadMethods(${i})">${i}</a></li>`;
    }
    
    // 下一页
    if (pagination.has_next) {
        html += `<li class="page-item"><a class="page-link" href="#" onclick="loadMethods(${pagination.page + 1})">下一页</a></li>`;
    }
    
    container.html(html);
}

function viewMethod(methodId) {
    $.ajax({
        url: `/dashboard/api/common-methods/${methodId}`,
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const method = response.data;
                const tags = method.tags ? JSON.parse(method.tags) : [];
                
                const content = `
                    <div class="row">
                        <div class="col-md-8">
                            <h5>${escapeHtml(method.name)}</h5>
                            <p class="text-muted">${method.description || '暂无描述'}</p>
                        </div>
                        <div class="col-md-4 text-end">
                            <span class="badge ${method.is_active ? 'bg-success' : 'bg-secondary'}">${method.is_active ? '激活' : '未激活'}</span>
                            <span class="badge ${method.is_public ? 'bg-info' : 'bg-warning'}">${method.is_public ? '公开' : '私有'}</span>
                        </div>
                    </div>
                    
                    <div class="row mt-3">
                        <div class="col-md-6">
                            <strong>创建者:</strong> ${escapeHtml(method.user_name)}
                        </div>
                        <div class="col-md-6">
                            <strong>使用次数:</strong> ${method.usage_count || 0}
                        </div>
                    </div>
                    
                    ${tags.length > 0 ? `
                        <div class="mt-3">
                            <strong>标签:</strong>
                            ${tags.map(tag => `<span class="badge bg-light text-dark me-1">${escapeHtml(tag)}</span>`).join('')}
                        </div>
                    ` : ''}
                    
                    <div class="mt-3">
                        <strong>代码内容:</strong>
                        <pre class="bg-light p-3 rounded"><code>${escapeHtml(method.content)}</code></pre>
                    </div>
                `;
                
                $('#viewMethodContent').html(content);
                $('#editMethodBtn').toggle(method.user_id == (window.currentUser ? window.currentUser.id : null));
                currentMethodId = methodId;
                // 使用Bootstrap 5的正确方式显示模态框
                const modal = new bootstrap.Modal(document.getElementById('viewMethodModal'));
                modal.show();
            } else {
                showToast('加载失败: ' + response.message, 'error');
            }
        },
        error: function() {
            showToast('加载失败: 网络错误，请稍后重试', 'error');
        }
    });
}

function editMethod(methodId = null) {
    if (methodId) {
        currentMethodId = methodId;
    }
    
    if (!currentMethodId) {
        return;
    }
    
    // 如果是从查看模态框打开的，先关闭查看模态框
    const viewModalElement = document.getElementById('viewMethodModal');
    let viewModal = bootstrap.Modal.getInstance(viewModalElement);
    if (!viewModal) {
        viewModal = new bootstrap.Modal(viewModalElement);
    }
    viewModal.hide();
    
    $.ajax({
        url: `/dashboard/api/common-methods/${currentMethodId}`,
        method: 'GET',
        success: function(response) {
            if (response.success) {
                const method = response.data;
                
                $('#methodId').val(method.id);
                $('#methodName').val(method.name);
                $('#methodDescription').val(method.description);
                $('#isPublic').prop('checked', method.is_public);
                $('#isActive').prop('checked', method.is_active);
                
                const tags = method.tags ? JSON.parse(method.tags) : [];
                $('#methodTags').val(tags.join(', '));
                
                codeEditor.setValue(method.content);
                
                $('#createMethodModalLabel').text('编辑公共方法');
                // 使用Bootstrap 5的正确方式显示模态框
                const modal = new bootstrap.Modal(document.getElementById('createMethodModal'));
                modal.show();
                
                // 确保编辑器在模态框显示后正确刷新
                setTimeout(function() {
                    codeEditor.refresh();
                    codeEditor.focus();
                }, 150);
            } else {
                showToast('加载失败: ' + response.message, 'error');
            }
        },
        error: function() {
            showToast('加载失败: 网络错误，请稍后重试', 'error');
        }
    });
}

function saveMethod() {
    const methodId = $('#methodId').val();
    const isEdit = !!methodId;
    
    const data = {
        name: $('#methodName').val().trim(),
        description: $('#methodDescription').val().trim(),
        content: codeEditor.getValue(),
        is_public: $('#isPublic').is(':checked'),
        is_active: $('#isActive').is(':checked'),
        tags: $('#methodTags').val().split(',').map(tag => tag.trim()).filter(tag => tag)
    };
    
    // 验证必填字段
    if (!data.name || !data.content) {
        showToast('验证失败: 请填写所有必填字段', 'error');
        return;
    }
    
    const url = isEdit ? `/dashboard/api/common-methods/${methodId}` : '/dashboard/api/common-methods';
    const method = isEdit ? 'PUT' : 'POST';
    
    $.ajax({
        url: url,
        method: method,
        contentType: 'application/json',
        data: JSON.stringify(data),
        success: function(response) {
            if (response.success) {
                showToast('保存成功: ' + response.message, 'success');
                // 使用Bootstrap 5的正确方式关闭模态框
                const modalElement = document.getElementById('createMethodModal');
                let modal = bootstrap.Modal.getInstance(modalElement);
                if (!modal) {
                    modal = new bootstrap.Modal(modalElement);
                }
                modal.hide();
                // 额外确保清理遮罩
                setTimeout(function() {
                    $('.modal-backdrop').remove();
                    $('body').removeClass('modal-open');
                    $('body').css('padding-right', '');
                }, 300);
                loadMethods(currentPage);
            } else {
                showToast('保存失败: ' + response.message, 'error');
            }
        },
        error: function() {
            showToast('保存失败: 网络错误，请稍后重试', 'error');
        }
    });
}

function deleteMethod(methodId, methodName) {
    if (!confirm(`确定要删除公共方法"${methodName}"吗？此操作不可撤销。`)) {
        return;
    }
    
    $.ajax({
        url: `/dashboard/api/common-methods/${methodId}`,
        method: 'DELETE',
        success: function(response) {
            if (response.success) {
                showToast('删除成功: ' + response.message, 'success');
                loadMethods(currentPage);
            } else {
                showToast('删除失败: ' + response.message, 'error');
            }
        },
        error: function() {
            showToast('删除失败: 网络错误，请稍后重试', 'error');
        }
    });
}

function copyImportStatement(importStatement) {
    // 使用现代浏览器的 Clipboard API
    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(importStatement).then(() => {
            showToast(importStatement, 'success');
        }).catch(() => {
            // 如果 Clipboard API 失败，使用备用方法
            fallbackCopyTextToClipboard(importStatement);
        });
    } else {
        // 备用方法：使用传统的 document.execCommand
        fallbackCopyTextToClipboard(importStatement);
    }
}

function fallbackCopyTextToClipboard(text) {
    const textArea = document.createElement("textarea");
    textArea.value = text;
    
    // 避免滚动到底部
    textArea.style.top = "0";
    textArea.style.left = "0";
    textArea.style.position = "fixed";
    
    document.body.appendChild(textArea);
    textArea.focus();
    textArea.select();
    
    try {
        const successful = document.execCommand('copy');
        if (successful) {
            showToast(text, 'success');
        } else {
            showToast('无法复制到剪贴板，请手动复制', 'error');
        }
    } catch (err) {
        showToast('浏览器不支持自动复制，请手动复制', 'error');
    }
    
    document.body.removeChild(textArea);
}



function resetMethodForm() {
    $('#methodForm')[0].reset();
    $('#methodId').val('');
    if (codeEditor) {
        codeEditor.setValue('');
        // 刷新编辑器确保正确显示
        setTimeout(function() {
            codeEditor.refresh();
        }, 50);
    }
    $('#createMethodModalLabel').text('新建公共方法');
    currentMethodId = null;
}



function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function formatDateTime(dateString) {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN');
}

// 使用全局的showMessage方法（在base.html中定义）
function showToast(message, type = 'info') {
    if (typeof window.showMessage === 'function') {
        window.showMessage(message, type, 3000);
    } else {
        // 如果全局函数不可用，回退到alert
        alert(message);
    }
}
</script>
{% endblock %}